/*
 * @Description  : http
 * @Author       : Keyman
 * @Date         : 2025-11-04 16:29:57
 * @LastEditors  : Keyman
 * @LastEditTime : 2025-11-20 10:55:38
 */

import axios from "axios";
import { message } from "antd";
import { store } from "../../store";
import type {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from "axios";

const http: AxiosInstance = axios.create({
  baseURL: "https://www.demo.com",
  timeout: 5000,
});

// 请求拦截器
http.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = store.getState().authSlice.token;
    if (token) {
      // 设置请求头
      // Bearer 表示一种认证类型
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response;
    if (data.code !== 200) {
      message.error(data.code + ":" + data.message);
      return Promise.reject(new Error(data.message || "Error"));
    }
    return response.data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default http;
